package au.edu.unsw.editingtool.transformxml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.xml.sax.SAXException;

/****************************************************
 * Using Xalan library to transform XML with XSL 
 * Parameters xml, xsl, outputFile are all absolute
 * pathnames. 
 * Return outputFile as formated.
 * Don't forget to clean temporary files.
 */

public class XMLProcessor {
	
	private String outputFile = "";
	private Source xml;
	private Source xsl;
	
	public void setOutFile(String name){
		this.outputFile = name;
	}
	
	public void setXml(String url) throws MalformedURLException, IOException {
		xml = new StreamSource(new URL("file", "", url).openStream());
	}
	
	public void setXsl(String url) throws MalformedURLException, IOException {
		xsl = new StreamSource(new URL("file", "", url).openStream());
	}
	
	public void clean() {
		(new File(this.outputFile)).delete();
	}
	
	public void reset() {
		this.outputFile = "";
		this.xml = null;
		this.xsl = null;
		//this.clean();
	}

	public String xmlProcessor(String path) 
		throws TransformerException, TransformerConfigurationException,
		 		SAXException, IOException, FileNotFoundException {
				
	    //transformer.setParameter(name, value);
	    	    
	    TransformerFactory factory = TransformerFactory.newInstance();
	    Transformer transformer = factory.newTransformer(this.xsl);

	    if (!(new File(this.outputFile)).exists()) {	    	
	    	this.outputFile = (new File(path)).getAbsolutePath();
	    }
	    
	    transformer.transform(this.xml,
	    					  new StreamResult(new java.io.FileOutputStream(this.outputFile)));
	    transformer.reset();
	    return this.outputFile;
	}

}